// 全局变量
let charts = {};
let selectedDevice = '';
let selectedTimeRange = 7;
let refreshInterval;
let refreshRate = 60; // 默认60秒刷新一次
let isLoggedIn = false;
let currentUser = '';

// DOM元素加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 初始化Bootstrap组件
    initBootstrapComponents();
    
    // 检查登录状态
    checkLoginStatus();
    
    // 设置事件监听器
    setupEventListeners();
    
    // 初始化图表
    initCharts();
});

// 初始化Bootstrap组件
function initBootstrapComponents() {
    // 初始化所有工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 初始化模态框
    const loginModal = new bootstrap.Modal(document.getElementById('loginModal'));
    const addDeviceModal = new bootstrap.Modal(document.getElementById('addDeviceModal'));
    const viewReportModal = new bootstrap.Modal(document.getElementById('viewReportModal'));
    
    // 将模态框实例存储为全局变量
    window.loginModal = loginModal;
    window.addDeviceModal = addDeviceModal;
    window.viewReportModal = viewReportModal;
}

// 检查登录状态
function checkLoginStatus() {
    // 这里应该调用后端API检查登录状态
    // 暂时模拟未登录状态，显示登录模态框
    isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    currentUser = localStorage.getItem('currentUser') || '';
    
    if (isLoggedIn && currentUser) {
        // 已登录，更新UI
        document.getElementById('currentUser').textContent = currentUser;
        document.getElementById('username').value = currentUser;
        
        // 加载数据
        loadDevices();
        updateDashboard();
        
        // 设置定时刷新
        startAutoRefresh();
    } else {
        // 未登录，显示登录模态框
        window.loginModal.show();
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 登录表单提交
    document.getElementById('loginSubmitBtn').addEventListener('click', handleLogin);
    
    // 登出按钮
    document.getElementById('logoutBtn').addEventListener('click', handleLogout);
    
    // 仪表盘控件
    document.getElementById('deviceSelect').addEventListener('change', (e) => {
        selectedDevice = e.target.value;
        updateDashboard();
    });
    
    document.getElementById('timeRange').addEventListener('change', (e) => {
        selectedTimeRange = parseInt(e.target.value);
        updateDashboard();
    });
    
    document.getElementById('refreshBtn').addEventListener('click', updateDashboard);
    
    // 添加设备按钮
    document.getElementById('addDeviceBtn').addEventListener('click', () => {
        window.addDeviceModal.show();
    });
    
    // 添加设备表单提交
    document.getElementById('addDeviceSubmitBtn').addEventListener('click', handleAddDevice);
    
    // 分析按钮
    document.getElementById('runAnalysisBtn').addEventListener('click', runAnalysis);
    
    // 刷新报告列表按钮
    document.getElementById('refreshReportsBtn').addEventListener('click', loadReports);
    
    // 用户信息表单提交
    document.getElementById('userInfoForm').addEventListener('submit', (e) => {
        e.preventDefault();
        updatePassword();
    });
    
    // 偏好设置表单提交
    document.getElementById('preferencesForm').addEventListener('submit', (e) => {
        e.preventDefault();
        savePreferences();
    });
    
    // 下载报告按钮
    document.getElementById('downloadReportBtn').addEventListener('click', downloadReport);
}

// 处理登录
async function handleLogin() {
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    const errorElement = document.getElementById('loginError');
    
    if (!username || !password) {
        errorElement.textContent = '请输入设备ID和密钥';
        errorElement.classList.remove('d-none');
        return;
    }
    
    try {
        // 修改为设备认证API
        const response = await fetch('/device/auth', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                device_id: username,
                secret: password 
            })
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            // 登录成功
            isLoggedIn = true;
            currentUser = username;
            
            // 保存登录状态到本地存储
            localStorage.setItem('isLoggedIn', 'true');
            localStorage.setItem('currentUser', username);
            
            // 更新UI
            document.getElementById('currentUser').textContent = username;
            document.getElementById('username').value = username;
            
            // 关闭登录模态框
            window.loginModal.hide();
            
            // 加载数据
            loadDevices();
            updateDashboard();
            
            // 设置定时刷新
            startAutoRefresh();
        } else {
            // 登录失败
            errorElement.textContent = data.message || '认证失败，请检查设备ID和密钥';
            errorElement.classList.remove('d-none');
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        errorElement.textContent = '登录请求失败，请稍后再试';
        errorElement.classList.remove('d-none');
    }
}

// 处理登出
async function handleLogout() {
    try {
        // 调用登出API
        const response = await fetch('/auth/logout', {
            method: 'POST'
        });
        
        // 无论成功与否，都清除本地登录状态
        isLoggedIn = false;
        currentUser = '';
        
        // 清除本地存储
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('currentUser');
        
        // 停止自动刷新
        stopAutoRefresh();
        
        // 显示登录模态框
        window.loginModal.show();
        
    } catch (error) {
        console.error('登出请求失败:', error);
    }
}

// 加载设备列表
async function loadDevices() {
    try {
        // 调用设备列表API
        const response = await fetch('/device/list');
        const data = await response.json();
        
        if (data.code === 0 && data.data) {
            const devices = data.data;
            
            // 更新设备选择下拉框
            updateDeviceSelects(devices);
            
            // 更新设备表格
            updateDeviceTable(devices);
        }
    } catch (error) {
        console.error('加载设备列表失败:', error);
    }
}

// 更新设备选择下拉框
function updateDeviceSelects(devices) {
    const selects = [
        document.getElementById('deviceSelect'),
        document.getElementById('analysisDeviceSelect'),
        document.getElementById('reportDeviceSelect')
    ];
    
    selects.forEach(select => {
        // 保留第一个选项
        const firstOption = select.options[0];
        select.innerHTML = '';
        select.appendChild(firstOption);
        
        // 添加设备选项
        devices.forEach(device => {
            const option = document.createElement('option');
            option.value = device.name;
            option.textContent = `${device.name} (${device.location || '未知位置'})`;
            select.appendChild(option);
        });
    });
}

// 更新设备表格
function updateDeviceTable(devices) {
    const tableBody = document.getElementById('deviceTableBody');
    tableBody.innerHTML = '';
    
    devices.forEach(device => {
        const row = document.createElement('tr');
        
        row.innerHTML = `
            <td>${device.uuid}</td>
            <td>${device.name}</td>
            <td>${device.location || '未设置'}</td>
            <td><span class="badge bg-success">在线</span></td>
            <td>
                <button class="btn btn-sm btn-primary view-device-btn" data-device-id="${device.name}">
                    <i class="bi bi-eye"></i>
                </button>
                <button class="btn btn-sm btn-warning edit-device-btn" data-device-id="${device.name}">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-sm btn-danger delete-device-btn" data-device-id="${device.name}">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
    
    // 添加设备按钮事件监听器
    document.querySelectorAll('.view-device-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const deviceId = btn.getAttribute('data-device-id');
            selectedDevice = deviceId;
            document.getElementById('deviceSelect').value = deviceId;
            
            // 切换到仪表盘标签
            document.querySelector('a[href="#dashboard"]').click();
            
            // 更新仪表盘
            updateDashboard();
        });
    });
    
    document.querySelectorAll('.edit-device-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const deviceId = btn.getAttribute('data-device-id');
            // 实现编辑设备功能
            alert(`编辑设备 ${deviceId} 功能待实现`);
        });
    });
    
    document.querySelectorAll('.delete-device-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const deviceId = btn.getAttribute('data-device-id');
            if (confirm(`确定要删除设备 ${deviceId} 吗？`)) {
                deleteDevice(deviceId);
            }
        });
    });
}

// 处理添加设备
async function handleAddDevice() {
    const deviceId = document.getElementById('deviceId').value;
    const deviceName = document.getElementById('deviceName').value;
    const deviceLocation = document.getElementById('deviceLocation').value;
    const deviceSecret = document.getElementById('deviceSecret').value;
    const errorElement = document.getElementById('addDeviceError');
    
    if (!deviceId || !deviceName || !deviceSecret) {
        errorElement.textContent = '请填写必填字段';
        errorElement.classList.remove('d-none');
        return;
    }
    
    try {
        // 调用添加设备API
        const response = await fetch('/device/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                device_id: deviceId,
                name: deviceName,
                location: deviceLocation,
                secret: deviceSecret
            })
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            // 添加成功
            window.addDeviceModal.hide();
            
            // 重置表单
            document.getElementById('addDeviceForm').reset();
            
            // 重新加载设备列表
            loadDevices();
            
            // 显示成功消息
            alert('设备添加成功');
        } else {
            // 添加失败
            errorElement.textContent = data.message || '添加设备失败';
            errorElement.classList.remove('d-none');
        }
    } catch (error) {
        console.error('添加设备请求失败:', error);
        errorElement.textContent = '添加设备请求失败，请稍后再试';
        errorElement.classList.remove('d-none');
    }
}

// 删除设备
async function deleteDevice(deviceId) {
    try {
        // 调用删除设备API
        const response = await fetch(`/device/delete?device_id=${deviceId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            // 删除成功
            loadDevices();
            alert('设备删除成功');
        } else {
            // 删除失败
            alert(data.message || '删除设备失败');
        }
    } catch (error) {
        console.error('删除设备请求失败:', error);
        alert('删除设备请求失败，请稍后再试');
    }
}

// 初始化图表
function initCharts() {
    const chartConfig = {
        type: 'line',
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            plugins: {
                tooltip: {
                    enabled: true,
                },
                legend: {
                    display: true,
                    position: 'top',
                },
            },
            scales: {
                x: {
                    type: 'time',
                    time: {
                        unit: 'hour',
                        displayFormats: {
                            hour: 'MM-DD HH:mm'
                        }
                    },
                    title: {
                        display: true,
                        text: '时间'
                    }
                },
                y: {
                    beginAtZero: false,
                    title: {
                        display: true,
                        text: '数值'
                    }
                }
            }
        },
        data: {
            datasets: []
        }
    };
    
    // 创建四个图表
    charts.temperature = new Chart(
        document.getElementById('temperatureChart'),
        {
            ...chartConfig,
            data: {
                datasets: []
            },
            options: {
                ...chartConfig.options,
                scales: {
                    ...chartConfig.options.scales,
                    y: {
                        ...chartConfig.options.scales.y,
                        title: {
                            display: true,
                            text: '温度 (°C)'
                        }
                    }
                }
            }
        }
    );
    
    charts.humidity = new Chart(
        document.getElementById('humidityChart'),
        {
            ...chartConfig,
            data: {
                datasets: []
            },
            options: {
                ...chartConfig.options,
                scales: {
                    ...chartConfig.options.scales,
                    y: {
                        ...chartConfig.options.scales.y,
                        title: {
                            display: true,
                            text: '湿度 (%)'
                        }
                    }
                }
            }
        }
    );
    
    charts.pm25 = new Chart(
        document.getElementById('pm25Chart'),
        {
            ...chartConfig,
            data: {
                datasets: []
            },
            options: {
                ...chartConfig.options,
                scales: {
                    ...chartConfig.options.scales,
                    y: {
                        ...chartConfig.options.scales.y,
                        title: {
                            display: true,
                            text: 'PM2.5 (μg/m³)'
                        }
                    }
                }
            }
        }
    );
    
    charts.co2 = new Chart(
        document.getElementById('co2Chart'),
        {
            ...chartConfig,
            data: {
                datasets: []
            },
            options: {
                ...chartConfig.options,
                scales: {
                    ...chartConfig.options.scales,
                    y: {
                        ...chartConfig.options.scales.y,
                        title: {
                            display: true,
                            text: 'CO₂ (ppm)'
                        }
                    }
                }
            }
        }
    );
}

// 更新仪表盘
async function updateDashboard() {
    if (!isLoggedIn) return;
    
    try {
        // 如果没有选择设备，使用第一个设备
        if (!selectedDevice && document.getElementById('deviceSelect').options.length > 1) {
            selectedDevice = document.getElementById('deviceSelect').options[1].value;
            document.getElementById('deviceSelect').value = selectedDevice;
        }
        
        if (!selectedDevice) {
            console.warn('没有可用的设备');
            return;
        }
        
        // 调用数据API
        const response = await fetch(`/data/query?device_id=${selectedDevice}&time_range=${selectedTimeRange}`);
        const data = await response.json();
        
        if (data.code === 0 && data.data) {
            // 更新图表
            updateCharts(data.data);
            
            // 更新指标卡片
            updateMetricCards(data.data.latest);
            
            // 更新最后更新时间
            document.getElementById('lastUpdate').textContent = `最后更新: ${new Date().toLocaleString()}`;
        }
    } catch (error) {
        console.error('更新仪表盘失败:', error);
    }
}

// 更新图表
function updateCharts(data) {
    if (!data.history || !data.history.length) {
        console.warn('没有历史数据');
        return;
    }
    
    // 准备图表数据
    const temperatureData = data.history.map(item => ({
        x: new Date(item.timestamp * 1000),
        y: item.avg_temperature
    }));
    
    const humidityData = data.history.map(item => ({
        x: new Date(item.timestamp * 1000),
        y: item.avg_humidity
    }));
    
    const pm25Data = data.history.map(item => ({
        x: new Date(item.timestamp * 1000),
        y: item.avg_pm2_5
    }));
    
    const co2Data = data.history.map(item => ({
        x: new Date(item.timestamp * 1000),
        y: item.avg_fresh_air // 假设CO2使用fresh_air字段
    }));
    
    // 更新图表数据
    charts.temperature.data.datasets = [{
        label: '平均温度',
        data: temperatureData,
        borderColor: 'rgba(255, 99, 132, 1)',
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderWidth: 2,
        tension: 0.4
    }];
    
    charts.humidity.data.datasets = [{
        label: '平均湿度',
        data: humidityData,
        borderColor: 'rgba(54, 162, 235, 1)',
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderWidth: 2,
        tension: 0.4
    }];
    
    charts.pm25.data.datasets = [{
        label: '平均PM2.5',
        data: pm25Data,
        borderColor: 'rgba(255, 206, 86, 1)',
        backgroundColor: 'rgba(255, 206, 86, 0.2)',
        borderWidth: 2,
        tension: 0.4
    }];
    
    charts.co2.data.datasets = [{
        label: '平均CO₂',
        data: co2Data,
        borderColor: 'rgba(75, 192, 192, 1)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderWidth: 2,
        tension: 0.4
    }];
    
    // 更新图表
    charts.temperature.update();
    charts.humidity.update();
    charts.pm25.update();
    charts.co2.update();
}

// 更新指标卡片
function updateMetricCards(latestData) {
    if (!latestData) {
        console.warn('没有最新数据');
        return;
    }
    
    // 更新温度
    document.getElementById('temperatureValue').textContent = `${latestData.avg_temperature.toFixed(1)}°C`;
    updateMetricStatus('temperature', latestData.avg_temperature);
    
    // 更新湿度
    document.getElementById('humidityValue').textContent = `${latestData.avg_humidity.toFixed(1)}%`;
    updateMetricStatus('humidity', latestData.avg_humidity);
    
    // 更新PM2.5
    document.getElementById('pm25Value').textContent = `${latestData.avg_pm2_5.toFixed(1)} μg/m³`;
    updateMetricStatus('pm25', latestData.avg_pm2_5);
    
    // 更新CO2（假设使用fresh_air字段）
    document.getElementById('co2Value').textContent = `${latestData.avg_fresh_air.toFixed(0)} ppm`;
    updateMetricStatus('co2', latestData.avg_fresh_air);
    
    // 更新臭氧
    document.getElementById('ozoneValue').textContent = `${latestData.avg_ozone.toFixed(2)} ppb`;
    updateMetricStatus('ozone', latestData.avg_ozone);
    
    // 更新二氧化氮
    document.getElementById('nitroDioValue').textContent = `${latestData.avg_nitro_dio.toFixed(2)} ppb`;
    updateMetricStatus('nitroDio', latestData.avg_nitro_dio);
    
    // 更新甲醛
    document.getElementById('methanalValue').textContent = `${latestData.avg_methanal.toFixed(3)} mg/m³`;
    updateMetricStatus('methanal', latestData.avg_methanal);
    
    // 更新一氧化碳
    document.getElementById('carbMomoValue').textContent = `${latestData.avg_carb_momo.toFixed(1)} ppm`;
    updateMetricStatus('carbMomo', latestData.avg_carb_momo);
}

// 更新指标状态
function updateMetricStatus(metric, value) {
    const statusElement = document.getElementById(`${metric}Status`);
    let status = '';
    let className = '';
    
    switch (metric) {
        case 'temperature':
            if (value < 18) {
                status = '偏低';
                className = 'status-warning';
            } else if (value > 28) {
                status = '偏高';
                className = 'status-danger';
            } else {
                status = '正常';
                className = 'status-good';
            }
            break;
            
        case 'humidity':
            if (value < 30) {
                status = '过干';
                className = 'status-warning';
            } else if (value > 70) {
                status = '过湿';
                className = 'status-danger';
            } else {
                status = '正常';
                className = 'status-good';
            }
            break;
            
        case 'pm25':
            if (value <= 35) {
                status = '优';
                className = 'status-good';
            } else if (value <= 75) {
                status = '良';
                className = 'status-warning';
            } else {
                status = '差';
                className = 'status-danger';
            }
            break;
            
        case 'co2':
            if (value < 800) {
                status = '良好';
                className = 'status-good';
            } else if (value < 1000) {
                status = '一般';
                className = 'status-warning';
            } else {
                status = '偏高';
                className = 'status-danger';
            }
            break;
            
        case 'ozone':
            if (value < 50) {
                status = '正常';
                className = 'status-good';
            } else if (value < 100) {
                status = '一般';
                className = 'status-warning';
            } else {
                status = '偏高';
                className = 'status-danger';
            }
            break;
            
        case 'nitroDio':
            if (value < 40) {
                status = '正常';
                className = 'status-good';
            } else if (value < 80) {
                status = '一般';
                className = 'status-warning';
            } else {
                status = '偏高';
                className = 'status-danger';
            }
            break;
            
        case 'methanal':
            if (value < 0.08) {
                status = '正常';
                className = 'status-good';
            } else if (value < 0.1) {
                status = '一般';
                className = 'status-warning';
            } else {
                status = '偏高';
                className = 'status-danger';
            }
            break;
            
        case 'carbMomo':
            if (value < 5) {
                status = '正常';
                className = 'status-good';
            } else if (value < 10) {
                status = '一般';
                className = 'status-warning';
            } else {
                status = '偏高';
                className = 'status-danger';
            }
            break;
    }
    
    statusElement.textContent = status;
    statusElement.className = `metric-status ${className}`;
}

// 运行数据分析
async function runAnalysis() {
    const deviceId = document.getElementById('analysisDeviceSelect').value;
    const analysisType = document.getElementById('analysisType').value;
    const timeRange = document.getElementById('analysisTimeRange').value;
    
    if (!deviceId) {
        alert('请选择设备');
        return;
    }
    
    // 显示加载状态
    const analysisContent = document.getElementById('analysisContent');
    analysisContent.innerHTML = `
        <div class="loading">
            <div class="loading-spinner"></div>
            <p class="mt-3">正在分析数据，请稍候...</p>
        </div>
    `;
    
    try {
        // 调用分析API
        const response = await fetch('/data/analyze', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                device_id: deviceId,
                analysis_type: analysisType,
                time_range: parseInt(timeRange)
            })
        });
        
        const data = await response.json();
        
        if (data.code === 0 && data.data) {
            // 更新分析结果
            document.getElementById('analysisTitle').textContent = getAnalysisTitle(analysisType);
            document.getElementById('analysisTime').textContent = `分析时间: ${new Date().toLocaleString()}`;
            
            // 格式化分析结果
            let formattedResult = '';
            
            if (typeof data.data === 'string') {
                formattedResult = data.data;
            } else {
                formattedResult = JSON.stringify(data.data, null, 2);
            }
            
            analysisContent.innerHTML = `<pre>${formattedResult}</pre>`;
            
            // 保存分析结果到报告列表
            saveAnalysisReport(deviceId, analysisType, timeRange, formattedResult);
        } else {
            // 分析失败
            analysisContent.innerHTML = `<p class="text-danger">分析失败: ${data.message || '未知错误'}</p>`;
        }
    } catch (error) {
        console.error('运行分析失败:', error);
        analysisContent.innerHTML = `<p class="text-danger">分析请求失败，请稍后再试</p>`;
    }
}

// 获取分析类型标题
function getAnalysisTitle(analysisType) {
    switch (analysisType) {
        case 'simple':
            return '简单数据分析';
        case 'anomaly':
            return '异常数据检测';
        case 'trend':
            return '数据趋势预测';
        case 'comprehensive':
            return '综合环境分析报告';
        default:
            return '数据分析结果';
    }
}

// 保存分析报告
async function saveAnalysisReport(deviceId, analysisType, timeRange, content) {
    try {
        // 调用保存报告API
        const response = await fetch('/data/save_report', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                device_id: deviceId,
                analysis_type: analysisType,
                time_range: parseInt(timeRange),
                content: content
            })
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            console.log('分析报告保存成功');
            // 刷新报告列表
            loadReports();
        } else {
            console.error('保存分析报告失败:', data.message);
        }
    } catch (error) {
        console.error('保存分析报告请求失败:', error);
    }
}

// 加载报告列表
async function loadReports() {
    const deviceId = document.getElementById('reportDeviceSelect').value;
    const reportType = document.getElementById('reportTypeSelect').value;
    
    try {
        // 构建查询参数
        let queryParams = '';
        if (deviceId) {
            queryParams += `device_id=${deviceId}&`;
        }
        if (reportType) {
            queryParams += `report_type=${reportType}&`;
        }
        
        // 调用报告列表API
        const response = await fetch(`/data/reports?${queryParams}`);
        const data = await response.json();
        
        if (data.code === 0 && data.data) {
            const reports = data.data;
            
            // 更新报告表格
            updateReportsTable(reports);
        }
    } catch (error) {
        console.error('加载报告列表失败:', error);
    }
}

// 更新报告表格
function updateReportsTable(reports) {
    const tableBody = document.getElementById('reportsTableBody');
    tableBody.innerHTML = '';
    
    if (!reports.length) {
        const row = document.createElement('tr');
        row.innerHTML = `<td colspan="6" class="text-center">暂无报告数据</td>`;
        tableBody.appendChild(row);
        return;
    }
    
    reports.forEach(report => {
        const row = document.createElement('tr');
        
        // 格式化时间范围
        let timeRangeText = '';
        switch (report.time_range) {
            case 1:
                timeRangeText = '最近24小时';
                break;
            case 7:
                timeRangeText = '最近7天';
                break;
            case 30:
                timeRangeText = '最近30天';
                break;
            default:
                timeRangeText = `最近${report.time_range}天`;
        }
        
        // 格式化报告类型
        let reportTypeText = '';
        switch (report.analysis_type) {
            case 'simple':
                reportTypeText = '简单分析';
                break;
            case 'anomaly':
                reportTypeText = '异常检测';
                break;
            case 'trend':
                reportTypeText = '趋势预测';
                break;
            case 'comprehensive':
                reportTypeText = '综合报告';
                break;
            default:
                reportTypeText = report.analysis_type;
        }
        
        row.innerHTML = `
            <td>${report.id}</td>
            <td>${report.device_id}</td>
            <td>${reportTypeText}</td>
            <td>${timeRangeText}</td>
            <td>${new Date(report.created_at).toLocaleString()}</td>
            <td>
                <button class="btn btn-sm btn-primary view-report-btn" data-report-id="${report.id}">
                    <i class="bi bi-eye"></i>
                </button>
                <button class="btn btn-sm btn-danger delete-report-btn" data-report-id="${report.id}">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
    
    // 添加报告按钮事件监听器
    document.querySelectorAll('.view-report-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const reportId = btn.getAttribute('data-report-id');
            viewReport(reportId);
        });
    });
    
    document.querySelectorAll('.delete-report-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const reportId = btn.getAttribute('data-report-id');
            if (confirm('确定要删除此报告吗？')) {
                deleteReport(reportId);
            }
        });
    });
}

// 查看报告
async function viewReport(reportId) {
    try {
        // 调用获取报告API
        const response = await fetch(`/data/report?report_id=${reportId}`);
        const data = await response.json();
        
        if (data.code === 0 && data.data) {
            const report = data.data;
            
            // 更新模态框内容
            document.getElementById('reportId').textContent = report.id;
            document.getElementById('reportDeviceId').textContent = report.device_id;
            
            // 格式化报告类型
            let reportTypeText = '';
            switch (report.analysis_type) {
                case 'simple':
                    reportTypeText = '简单分析';
                    break;
                case 'anomaly':
                    reportTypeText = '异常检测';
                    break;
                case 'trend':
                    reportTypeText = '趋势预测';
                    break;
                case 'comprehensive':
                    reportTypeText = '综合报告';
                    break;
                default:
                    reportTypeText = report.analysis_type;
            }
            document.getElementById('reportType').textContent = reportTypeText;
            
            // 格式化时间范围
            let timeRangeText = '';
            switch (report.time_range) {
                case 1:
                    timeRangeText = '最近24小时';
                    break;
                case 7:
                    timeRangeText = '最近7天';
                    break;
                case 30:
                    timeRangeText = '最近30天';
                    break;
                default:
                    timeRangeText = `最近${report.time_range}天`;
            }
            document.getElementById('reportTimeRange').textContent = timeRangeText;
            
            document.getElementById('reportGeneratedAt').textContent = new Date(report.created_at).toLocaleString();
            document.getElementById('reportContent').innerHTML = `<pre>${report.content}</pre>`;
            
            // 显示模态框
            window.viewReportModal.show();
        } else {
            alert(data.message || '获取报告失败');
        }
    } catch (error) {
        console.error('查看报告请求失败:', error);
        alert('查看报告请求失败，请稍后再试');
    }
}

// 删除报告
async function deleteReport(reportId) {
    try {
        // 调用删除报告API
        const response = await fetch(`/data/delete_report?report_id=${reportId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            // 删除成功
            loadReports();
            alert('报告删除成功');
        } else {
            // 删除失败
            alert(data.message || '删除报告失败');
        }
    } catch (error) {
        console.error('删除报告请求失败:', error);
        alert('删除报告请求失败，请稍后再试');
    }
}

// 下载报告
function downloadReport() {
    const reportId = document.getElementById('reportId').textContent;
    const reportType = document.getElementById('reportType').textContent;
    const reportDeviceId = document.getElementById('reportDeviceId').textContent;
    const reportContent = document.getElementById('reportContent').textContent;
    
    // 创建Blob对象
    const blob = new Blob([reportContent], { type: 'text/plain' });
    
    // 创建下载链接
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${reportType}_${reportDeviceId}_${reportId}.txt`;
    
    // 触发下载
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

// 更新密码
async function updatePassword() {
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    if (!currentPassword || !newPassword || !confirmPassword) {
        alert('请填写所有密码字段');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        alert('新密码和确认密码不匹配');
        return;
    }
    
    try {
        // 调用更新密码API
        const response = await fetch('/user/update_password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword
            })
        });
        
        const data = await response.json();
        
        if (data.code === 0) {
            // 更新成功
            alert('密码更新成功');
            
            // 清空表单
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
        } else {
            // 更新失败
            alert(data.message || '密码更新失败');
        }
    } catch (error) {
        console.error('更新密码请求失败:', error);
        alert('更新密码请求失败，请稍后再试');
    }
}

// 保存偏好设置
function savePreferences() {
    const theme = document.getElementById('theme').value;
    const dataRefreshInterval = parseInt(document.getElementById('dataRefreshInterval').value);
    
    if (dataRefreshInterval < 30) {
        alert('刷新间隔不能小于30秒');
        return;
    }
    
    // 保存设置到本地存储
    localStorage.setItem('theme', theme);
    localStorage.setItem('dataRefreshInterval', dataRefreshInterval);
    
    // 应用主题
    applyTheme(theme);
    
    // 更新刷新间隔
    refreshRate = dataRefreshInterval;
    
    // 重启自动刷新
    restartAutoRefresh();
    
    alert('设置已保存');
}

// 应用主题
function applyTheme(theme) {
    // 实现主题切换逻辑
    if (theme === 'dark') {
        document.body.classList.add('dark-theme');
    } else {
        document.body.classList.remove('dark-theme');
    }
}

// 加载偏好设置
function loadPreferences() {
    const theme = localStorage.getItem('theme') || 'light';
    const dataRefreshInterval = parseInt(localStorage.getItem('dataRefreshInterval') || '60');
    
    document.getElementById('theme').value = theme;
    document.getElementById('dataRefreshInterval').value = dataRefreshInterval;
    
    // 应用主题
    applyTheme(theme);
    
    // 更新刷新间隔
    refreshRate = dataRefreshInterval;
}

// 开始自动刷新
function startAutoRefresh() {
    // 先停止现有的刷新
    stopAutoRefresh();
    
    // 设置新的刷新间隔
    refreshInterval = setInterval(() => {
        updateDashboard();
    }, refreshRate * 1000);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
}

// 重启自动刷新
function restartAutoRefresh() {
    stopAutoRefresh();
    startAutoRefresh();
}

// 页面加载完成后，加载偏好设置
window.addEventListener('load', loadPreferences);